package com.yida.system.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.yida.common.core.constant.CacheConstants;
import com.yida.common.core.enums.EnableTypeEnum;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.redis.service.RedisService;
import com.yida.system.domain.request.SysBlackConfigEditRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.yida.system.mapper.SysBlackConfigMapper;
import com.yida.system.api.domain.SysBlackConfig;
import com.yida.system.service.ISysBlackConfigService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统黑名单配置Service业务层处理
 * 
 * @author wws
 * @date 2023-03-22
 */
@Service
@RequiredArgsConstructor
public class SysBlackConfigServiceImpl implements ISysBlackConfigService 
{
    private final SysBlackConfigMapper sysBlackConfigMapper;

    private final RedisService redisService;

    /**
     * 查询系统黑名单配置
     * 
     * @param id 系统黑名单配置主键
     * @return 系统黑名单配置
     */
    @Override
    public SysBlackConfig selectSysBlackConfigById(Long id)
    {
        return sysBlackConfigMapper.selectSysBlackConfigById(id);
    }

    /**
     * 查询系统黑名单配置列表
     * 
     * @param sysBlackConfig 系统黑名单配置
     * @return 系统黑名单配置
     */
    @Override
    public List<SysBlackConfig> selectSysBlackConfigList(SysBlackConfig sysBlackConfig)
    {
        return sysBlackConfigMapper.selectSysBlackConfigList(sysBlackConfig);
    }

    /**
     * 修改系统黑名单配置
     * 
     * @param editRequest 系统黑名单配置
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSysBlackConfig(SysBlackConfigEditRequest editRequest)
    {
        // 查询黑名单配置
        SysBlackConfig sysBlackConfig = sysBlackConfigMapper.selectSysBlackConfigById(editRequest.getId());
        if(ObjectUtil.isEmpty(sysBlackConfig)){
            throw new ServiceException("未查询到对应系统黑名单配置");
        }
        // 拷贝参数
        BeanUtil.copyProperties(editRequest,sysBlackConfig);
        // 保存系统黑名单配置
        sysBlackConfig.setUpdateTime(DateUtils.getNowDate());
        int result = sysBlackConfigMapper.updateSysBlackConfig(sysBlackConfig);
        if(1 != result){
            throw new ServiceException("黑名单配置修改失败");
        }
        // 判断黑名单启用状态
        if (EnableTypeEnum.LOCK.getType().equals(sysBlackConfig.getStatus())) {
            redisService.deleteObject(CacheConstants.BLACK_CONFIG_KEY);
        }
        else if (EnableTypeEnum.UNLOCK.getType().equals(sysBlackConfig.getStatus())) {
            redisService.setCacheObject(CacheConstants.BLACK_CONFIG_KEY, JSONUtil.parse(sysBlackConfig));
        }
        else {
            throw new ServiceException("黑名单配置启用状态异常");
        }

        return result;
    }

}
